package net.wicp.tams.common.binlog.self.event;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.binlog.self.bean.EventBean;
import net.wicp.tams.common.binlog.self.sender.ISender;

@Slf4j
public class GtidEvent extends AbsEvent {
	private int flags;
	private long gno;
	private String source;

	private String gtid;

	public GtidEvent(EventBean event) {
		super(event);
	}

	@Override
	public Result parseBody(ISender... senders) {
		rowlog("GtidEvent事件的body位置");
		flags = super.logBuffer.getUint8();
		byte[] sid = super.logBuffer.getData(16);// assitRead.readBytes(16);
		gno = super.logBuffer.getLong64();// ByteUtil.readLongL(assitRead.readBytes(8));
		source = byteArrayToHex(sid, 0, 4) + "-" + byteArrayToHex(sid, 4, 2) + "-" + byteArrayToHex(sid, 6, 2) + "-"
				+ byteArrayToHex(sid, 8, 2) + "-" + byteArrayToHex(sid, 10, 6);
		gtid = source + ":" + String.format("%d", gno);
		log.info("---------------------gtid:[{}]----------------------------------", gtid);
		return Result.getSuc();
	}

	private String byteArrayToHex(byte[] a, int offset, int len) {
		StringBuilder sb = new StringBuilder();
		for (int idx = offset; idx < (offset + len) && idx < a.length; idx++) {
			sb.append(String.format("%02x", a[idx] & 0xff));
		}
		return sb.toString();
	}

	public long getGno() {
		return this.gno;
	}

	public String getGtid() {
		return this.gtid;
	}

	public String getSource() {
		return source;
	}

}
